package com.alibaba.nacos.common.task.engine;

import com.alibaba.nacos.common.task.AbstractExecuteTask;
import com.alibaba.nacos.common.task.NacosTask;
import com.alibaba.nacos.common.task.NacosTaskProcessor;
import lombok.SneakyThrows;

import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;

public class TaskExecuteWorker implements NacosTaskProcessor, Closeable {

    private final BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1 << 15);
    private final AtomicBoolean closed = new AtomicBoolean(false);
    private Thread thread = Thread.startVirtualThread(this::doRun);

    @SneakyThrows
    @Override
    public boolean process(NacosTask task) {
        if (task instanceof AbstractExecuteTask abstractExecuteTask) {
            queue.put(abstractExecuteTask);
        }
        return true;
    }

    @SneakyThrows
    private void doRun() {
        while (!closed.get()) {
            Runnable task = queue.take();
            task.run();
        }
    }

    @Override
    public void close() throws IOException {

    }
}
